<?php

	require_once "config.php";
	require_once dirname(__FILE__). '/util/connection.class.php';
	require_once dirname(__FILE__). '/util/TimeUtil.php';
	require_once dirname(__FILE__). '/util/record.php';
	set_time_limit(60*60);
	ini_set('memory_limit', '512M');

	$g_start = microtime(true);

	$tag = 'offersofweek';
	$dbconn = Connection::getInstance();
	
	$emailEvents = getActivedEmailEvents($dbconn);
	foreach($emailEvents as $eventId => $emailEvent){
		$eventName = $emailEvent['event_name'];
		$logic = $emailEvent['logic'];
		$templateId = $emailEvent['template_id'];
		$eventUsers = getUsersByConditions($emailEvent['conditions'], $logic, $dbconn);
		if(!empty($eventUsers)){
			foreach($eventUsers as $k => $user){
				$site = getSiteInfo($user['site_id'], $dbconn);
				$args = array();
				$args['firstname'] = $user['firstname'];
				
				$template = geteEmailTemplateById($templateId, $site, $dbconn);
				$translatedSubject = translate($template['template_subject'], $args);
				$emailId = addSentEmailToDb($site['name'], 'no-reply@' . strtolower($site['domain']), $translatedSubject, $user['email'], $dbconn);
						
				$record = new Record($user['id']);
				$record->addEmailSentRecording('emailflow', date('Y-m-d'));

				$args['emailId'] = $emailId;
				$args['eventId'] = $eventId;
				$translatedTemplate = translate($template['content'], $args);
				updateEmailId($emailId, $translatedTemplate, $dbconn);			
			}
		}
	}
	
	echo ''. microtime(true) - $g_start . "seconds \n";
	echo "memory: " . memory_get_peak_usage() . " bytes \n";
	
	
	
	function getActivedEmailEvents($dbconn)
	{
		try{
			$sql = " SELECT e.id, e.event_name, e.logic, t.id AS template_id, c.factor, c.relation, c.val FROM email_events e LEFT JOIN email_templates t ON e.template_id=t.id LEFT JOIN email_condition c ON e.id=c.event_id WHERE e.actived!=0 ";
			$result = $dbconn->query($sql);
			if(count($result) > 0){
				$eventsInfo = array();
				foreach($result as $k => $eventInfo){
					$eventsInfo[$eventInfo['id']]['event_name'] = $eventInfo['event_name'];
					$eventsInfo[$eventInfo['id']]['logic'] = $eventInfo['logic'];
					$eventsInfo[$eventInfo['id']]['template_id'] = $eventInfo['template_id'];
					$eventsInfo[$eventInfo['id']]['conditions'][] = array(
						'factor' => $eventInfo['factor'],
						'relation' => $eventInfo['relation'],
						'val' => $eventInfo['val']
					);
				}
				return $eventsInfo;
			}
			return false;
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}	
	}
	
	function getUsersByConditions($conditions, $logic, $dbconn)
	{
		try{
			$query = array();
			$vars = array();
			foreach($conditions as $k => $condition){
				$conditionTranslated = conditionTrans($condition);
				$query[] = $conditionTranslated['factor'] . $conditionTranslated['relation'] . '?';
				$vars[] = $conditionTranslated['val'];
			}
			
			$sql = " SELECT * FROM users ";
			if(!empty($query)){
				$sql .= ' WHERE ' . implode(' '.$logic.' ', $query);
			}
			return $dbconn->query($sql, $vars);
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}		
	}
	
	function conditionTrans($condition)
	{
		switch($condition['factor']){
			case 'age':
				$factor = 'birthday';
				$relation = reverseRelation($condition['relation']);
				$val = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d'), date('Y')-$condition['val']));
				break;
			case 'gender':
				$factor = 'gender';
				$relation = '=';
				if($condition['val'] == '0'){
					$val = 'F';
				}else if($condition['val'] == '1'){
					$val = 'M';
				}else{
					$relation = '!=';
					$val = '';
				}
				break;
			case 'site':
				$factor = 'site_id';
				$relation = $condition['relation'];
				$val = $condition['val'];
				break;
			case 'livetime':
				$factor = 'created';
				$relation = reverseRelation($condition['relation']);
				list($time, $unit) = explode('-', $condition['val']);
				if(strtolower($unit) == 'y'){
					$val = mktime(0, 0, 0, date('m'), date('d'), date('Y')-$time);
				}else if(strtolower($unit) == 'm'){
					$val = mktime(0, 0, 0, date('m')-$time, date('d'), date('Y'));
				}else{
					$val = mktime(0, 0, 0, date('m'), date('d')-$time, date('Y'));
				}
				break;
			case 'inactive':
				$factor = 'last_visit';
				$relation = reverseRelation($condition['relation']);
				list($time, $unit) = explode('-', $condition['val']);
				if(strtolower($unit) == 'y'){
					$val = mktime(0, 0, 0, date('m'), date('d'), date('Y')-$time);
				}else if(strtolower($unit) == 'm'){
					$val = mktime(0, 0, 0, date('m')-$time, date('d'), date('Y'));
				}else{
					$val = mktime(0, 0, 0, date('m'), date('d')-$time, date('Y'));
				}
				break;
			default:
				$factor = $condition['factor'];
				$relation = $condition['relation'];
				$val = $condition['val'];
		}
		
		return array(
			'factor' => $factor,
			'relation' => $relation,
			'val' => $val
		);
	}
	
	function reverseRelation($relation)
	{
		$relation = str_replace(' ', '', $relation);
		if($relation == '>'){
			$relation = '<';
		}else if($relation == '>='){
			$relation = '<=';
		}else if($relation == '<'){
			$relation = '>';
		}else if($relation == '<='){
			$relation = '>=';
		}
		
		return $relation;
	}
	
	

	function getSiteInfo($siteId, $dbconn) {
		$sql = 'SELECT id, domain, name, template FROM sites WHERE id=?';
		try{
			$site =  $dbconn->query($sql, array($siteId));
			if(count($site) > 0){
				return $site[0];
			}
			return false;
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}

	function getHeaderFootTemplate($site_template, $dbconn){
		$template_header_name = TEMPLATE_ROOT . '/' . $site_template . '/email/header.html';
		$template_foot_name = TEMPLATE_ROOT . '/' . $site_template . '/email/foot.html';
		$templateHeaderFoot = array();
		if(file_exists($template_header_name)){
			if(is_readable($template_header_name)){
				$templateHeaderFoot['header'] = file_get_contents($template_header_name);
			}
		}
		
		if(file_exists($template_foot_name)){
			if(is_readable($template_foot_name)){
				$templateHeaderFoot['foot'] = file_get_contents($template_foot_name);
			}
		}
		return $templateHeaderFoot;
	}

	function geteEmailTemplateById($template_id, $site, $dbconn)
	{
		try{
			$sql = " SELECT * FROM email_templates WHERE id=? ";
			$result = $dbconn->query($sql, array($template_id));
			if(count($result) > 0){
				$template = $result[0];
				$templateHeadFoot = getHeaderFootTemplate($site['template'], $dbconn);
				$template['content'] = $templateHeadFoot['header'] . $template['content'] . $templateHeadFoot['foot'];
				return $template;
			}
			return false;
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	function addSentEmailToDb($sender, $sendfrom, $subject, $sendto, Connection $db){
		$sql = "insert into emails set sender=?, sendfrom=?, subject=?, sendto=?, created=?, sent=?, priority=10, email_type='emailflow'";
		try{
			return $db->execute($sql,array($sender, $sendfrom, $subject, $sendto, time(), 0), true);
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	function updateEmailId ($id, $content, $db) {
		$sql = "update emails set content=? where id=?";
		try{
			return $db->execute($sql,array($content, $id));
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	function translate($content, $args){
		foreach ($args as $k => $v){
			$content = str_replace('[[' . $k . ']]', $v, $content);
		}
		return $content;
	}

	
	